<template>
  <div class="table-container">
    <vab-query-form>
      <vab-query-form-left-panel>
        <el-button
          v-if="false"
          v-popover:popoverAll
          type="primary"
          icon="el-icon-upload2"
        >
          导出Excel
        </el-button>
        <el-button
          v-if="false"
          v-popover:popoverPart
          type="primary"
          icon="el-icon-upload2"
        >
          导出选中行
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-left-panel>
        <el-cascader
          v-if="user.level <= 1"
          :options="townToVillage"
          :props="townToVillProp"
          placeholder="地区筛选"
          change-on-select
          clearable
          @change="townToVillageChange"
        />
        <el-select
          v-if="user.level == 2"
          v-model="queryForm.village"
          multiple
          placeholder="地区筛选"
          clearable
          @change="villageChange"
        >
          <el-option
            v-for="village in queryVillageAtt"
            :key="village.id"
            :label="village.name"
            :value="village.id"
          />
        </el-select>
        <el-form
          ref="form"
          :model="queryForm"
          :inline="true"
          @submit.native.prevent
        >
          <el-form-item>
            <el-input
              v-model="queryForm.keyword"
              placeholder="查询内容或字段"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              type="primary"
              native-type="submit"
              @click="handleQuery"
            >
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-left-panel>
    </vab-query-form>
    <el-table
      ref="tableSort"
      v-loading="listLoading"
      :data="list"
      :element-loading-text="elementLoadingText"
      @selection-change="setSelectRows"
      @sort-change="tableSortChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        label="序号"
        width="95"
      >
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        prop="village.town.name"
        label="所属街道"
      />
      <el-table-column
        prop="village.name"
        label="所属村"
      />
      <el-table-column
        prop="title"
        label="反馈标题"
      />
      <el-table-column
        prop="content"
        label="反馈内容"
      />
      <el-table-column
        v-if="user.level < 3"
        prop="upMessage"
        label="向上反馈原因"
      >
        <template slot-scope="scope">
          <el-popover
            ref="popover"
            placement="top-start"
            title="向上反馈原因"
            width="200"
            trigger="hover"
            :content="scope.row.upMessage"
          />
          <el-button
            v-popover:popover
            type="text"
          >
            {{ scope.row.upMessage }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        v-if="user.level > 1"
        prop="downMessage"
        label="退回反馈原因"
      >
        <template slot-scope="scope">
          <el-popover
            ref="popover1"
            placement="top-start"
            title="退回反馈原因"
            width="200"
            trigger="hover"
            :content="scope.row.downMessage"
          />
          <el-button
            v-popover:popover1
            type="text"
          >
            {{ scope.row.downMessage }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="500px"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            v-if="user.level > 1"
            type="primary"
            icon="el-icon-sort-up"
            @click="upwardFeedback(scope.row)"
          >
            向上反馈
          </el-button>
          <el-button
            v-if="scope.row.reseted == false"
            type="success"
            icon="el-icon-edit"
            @click="handleFeedback(scope.row)"
          >
            处理反馈
          </el-button>
          <el-button
            v-if="scope.row.reseted == true"
            type="info"
            icon="el-icon-circle-close"
            @click="handleFeedback(scope.row)"
          >
            处理反馈-被退回过
          </el-button>
          <el-button
            v-if="user.level < 3"
            type="warning"
            icon="el-icon-sort-down"
            @click="returnFeedback(scope.row)"
          >
            退回反馈
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :background="background"
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />

    <!-- 导出Excel -->
    <el-popover
      ref="popoverAll"
      placement="right"
      width="250"
      trigger="click"
    >
      <vab-query-form>
        <vab-query-form-left-panel :span="24">
          <el-form
            label-position="right"
            :inline="false"
            size="mini"
            @submit.native.prevent
          >
            <el-form-item label="文件名">
              <el-input
                v-model="filename"
                placeholder="请输出要导出文件的名称"
                clearable
              />
            </el-form-item>
            <el-form-item label="文件类型">
              <el-select v-model="bookType">
                <el-option
                  v-for="item in options"
                  :key="item"
                  :label="item"
                  :value="item"
                  clearable
                />
              </el-select>
            </el-form-item>
            <el-form-item label="自动列宽">
              <el-radio-group v-model="autoWidth">
                <el-radio :label="true">
                  是
                </el-radio>
                <el-radio :label="false">
                  否
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                @click="allHandleDownload"
              >
                导出 Excel
              </el-button>
            </el-form-item>
          </el-form>
        </vab-query-form-left-panel>
      </vab-query-form>
    </el-popover>
    <!-- 导出选中行 -->
    <el-popover
      ref="popoverPart"
      placement="right"
      width="250"
      trigger="click"
    >
      <vab-query-form>
        <vab-query-form-left-panel>
          <el-form
            :inline="true"
            @submit.native.prevent
          >
            <el-form-item>
              <el-input
                v-model="filename"
                placeholder="请输出要导出文件的名称"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="partHandleDownload()"
              >
                导出选中行
              </el-button>
            </el-form-item>
          </el-form>
        </vab-query-form-left-panel>
      </vab-query-form>
    </el-popover>

    <el-dialog
      title="反馈处理回复"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :lock-scroll="true"
      :fullscreen="true"
      @close="dialogFormVisible = false"
    >
      <el-row>
        <el-col :span="12">
          <div class="grid-content">
            <el-form
              :model="showForm"
              :status-icon="true"
              label-width="80px"
            >
              <el-form-item
                label="所属村"
              >
                <el-cascader
                  v-model="showForm.villageWrap"
                  :options="villageCascader"
                  :props="villageProp"
                  placeholder="请选择所属村"
                  :show-all-levels="false"
                  clearable
                  disabled
                  @change="change"
                />
              </el-form-item>
              <el-form-item
                label="村民"
              >
                <el-select
                  v-model="showForm.villager"
                  placeholder="请选择对应村民"
                  disabled
                >
                  <el-option
                    v-for="item in villagerAtt"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="标题"
              >
                <el-input
                  v-model.trim="showForm.title"
                  autocomplete="off"
                  placeholder="请输入标题"
                  disabled
                  clearable
                />
              </el-form-item>
              <el-form-item
                label="内容"
              >
                <el-input
                  v-model.trim="showForm.content"
                  type="textarea"
                  autocomplete="off"
                  placeholder="请输入内容"
                  disabled
                  clearable
                />
              </el-form-item>

              <relatedDocuments
                :related-documents="documents"
                disabled
              />
            </el-form>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content">
            <el-form
              ref="form"
              :model="res"
              :status-icon="true"
              label-width="80px"
            >
              <el-form-item
                label="回复内容"
              >
                <vue-editor
                  v-model="res.handlRes"
                  use-custom-image-handler
                  @image-added="handleImageAdded"
                />
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
      
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button
          type="primary"
          @click="handle"
        >
          确定回复 
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//手动添加
import { VueEditor } from "vue2-editor";
import { mapGetters } from "vuex";
import relatedDocuments from "@/components/My-Components/relatedDocuments";
export default {
  name: "MyTable",
  computed: {
    ...mapGetters({
      user: "user/info",
    }),
  },
  components: {
    VueEditor,
    relatedDocuments,
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      list: [],
      listLoading: false,
      layout: "total, sizes, prev, pager, next, jumper",
      total: 0,
      background: true,
      selectRows: "",
      elementLoadingText: "正在加载...",
      queryForm: {
        pageNo: 1,
        pageSize: 20,
        town: "",
        village: "",
        keyword: "",
        status: "",
      },

      showForm: {
        villageWrap: "",
        title: "",
        content: "",
      },

      // excle 导出
      filename: "区相关信息",
      autoWidth: true,
      bookType: "xlsx",
      options: ["xlsx", "csv", "txt"],

      table: {},
      selectedData: {},
      sort: [],

      res: {
        processed: true,
        handler: "",
        handlRes: "",
      },
      dialogFormVisible : false,
      handlingFeedback: {},

      // 搜索
      townToVillProp: {
        value: "id",
        label: "name",
        children: "village"
      },
      townToVillage: [],
      queryVillageAtt: [],

      villageCascader: [],
      villageProp: {
        value: "id",
        label: "name",
      },
      relatedDocuments: "",
      documents: "",
      villagerAtt: [],
    };
  },
  created() {
    this.init()
    this.showInit()
    this.fetchData();
  },
  beforeDestroy() {},
  mounted() {},
  methods: {
    tableSortChange(column) {
      // const imageList = [];
      // this.$refs.tableSort.tableData.forEach((item, index) => {
      //   imageList.push(item.img);
      // });
      if(column.order) {
        this.sort = [`${column.prop},${column.order == 'descending' ? 'DESC': 'ASC'}`]
      } else {
        this.sort = []
      }
      this.fetchData()
    },
    setSelectRows(val) {
      this.selectRows = val;
      this.selectedData = this.transformData(val)
    },
    handleAdd() {
      this.$refs["edit"].showEdit();
    },
    handleEdit(row) {
      this.$refs["edit"].showEdit(row);
    },
    handleSizeChange(val) {
      this.queryForm.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.queryForm.pageNo = val;
      this.fetchData();
    },
    handleQuery() {
      this.queryForm.pageNo = 1;
      this.fetchData();
    },
    getQuery() {
      let query  = JSON.parse(JSON.stringify(this.queryForm))
      let fields = ""
      let  s = {
        "$or": [
          {
            "village.name": {
              "$cont": query.keyword
            }
          },
        ],
        "processed": {
          "$eq": false
        },
        "status": {
          //特别注意 此操作
          "$eq": query.status.toString()
        },
        init() {
          if(query.village) {
            if(Array.isArray(query.village) && query.village.length > 0) {
              this['village.id'] = {
                "$in": query.village 
              }
            } else if (!Array.isArray(query.village)) {
              this['village.id'] = {
                "$eq": query.village 
              }
            }
          }
          if(query.town) {
            this['village.town.id'] = {
              "$eq": query.town 
            }
          }
          return this
        }
      }
      console.log(query)
      let filterInfo = (query.village !== "" && query.village && (Array.isArray(query.village) ? query.village.length > 0 : true)) ? `filter=village.town.id||$eq||${query.town}&filter=village.id||$in||${query.village.toString()}`: 
                       ((query.town !== "" && query.town) ? `filter=village.town.id||$eq||${query.town}` : "")
      let or = ""
      let sort = `${this.sort.map(item => `sort=${item}`).join('&')}&sort=createdAt,DESC`
      let join = `join=village&join=village.town&join=villager`
      let pageInfo = `limit=${query.pageSize}&page=${query.pageNo}`
      
      //列排序 列名 排序规则 ASC(递增),DESC(递降)
      //粗略搜索
      // let search = ''
      return `fields=${fields}&s=${JSON.stringify(s.init())}&${filterInfo}&or=${or}&${sort}&${join}&${pageInfo}`
    },
    async fetchData() {
      this.listLoading = true;
      let res = await this.$http.get("feedback" + `?${this.getQuery()}`);
      this.list = res.data.data;
      this.total = res.data.total;
      this.listLoading = false;
      this.table = this.transformData(this.list)
      console.log(this.table)
    },
    
    transformData(objectData) {
      let header = []
      let data = []
      if(objectData.length > 0) {
        for (const key in objectData[0]) {
           header.push(key)
        }
        objectData.forEach(item => {
          let att = []
          header.forEach( key => att.push(item[key]))
          data.push(att)
        })
      }
      return {
        header,
        data
      }
    },
    //excel 导出
    allHandleDownload() {
      import("@/vendor/ExportExcel").then((excel) => {
          const  { header, data }  =  this.table;
          excel.export_json_to_excel({
            header,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType,
          });
      });
    },
    partHandleDownload () {
      if(Array.isArray(this.selectedData.data) && this.selectedData.data.length > 0) {
        import("@/vendor/ExportExcel").then((excel) => {
          const { header, data }  =  this.selectedData;
          excel.export_json_to_excel({
            header,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType,
          });
        });
      } else {
        this.$baseMessage("请至少选择一行", "error");
      }
    },

    async init() {
      this.setQuery()
      if(this.user.level <= 1) {
        const res = await this.$http.get(`town?join=village`)
        this.townToVillage = res.data
      }else if(this.user.level == 2) {
        const res = await this.$http.get(`town/${this.user.town.id}`)
        this.queryVillageAtt = res.data.village
      }
    },
    async showInit() {
      const res = await this.$http.get(`area?join=town&join=town.village`);
      res.data.forEach(area => {
        area.children = area.town
        area.town.forEach(town => {
          town.children = town.village
        })
      })
      this.villageCascader = res.data;
    },
    async change(val) {
      this.showForm.village = val[val.length - 1];
      const res = await this.$http.get(`village/${this.showForm.village}?join=villager`)
      console.log(res.data.villager)
      this.villagerAtt = res.data.villager
    },
    setQuery() {
      if(this.user.level == 1) {
        this.queryForm.status = 2
      } else if(this.user.level == 2) {
        this.queryForm.status = 1
        this.queryForm.town = this.user.town.id
        console.log(this.queryForm.town)
      } else if (this.user.level == 3) {
        this.queryForm.status = 0
        this.queryForm.town = this.user.town.id
        this.queryForm.village = this.user.village.id
      }
    },
    townToVillageChange(att) {
      this.queryForm.town = att[0]
      this.queryForm.village = att[1] || ""
      this.fetchData()
    },
    villageChange(att) {
      this.fetchData()
    },

    async upwardFeedback(feedback) {
      this.$baseConfirm("你确定要向上反馈当前项吗", null, async () => {
        this.$prompt('请输入向上级反馈原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(async ({ value }) => {
          let obj = JSON.parse(JSON.stringify(feedback))
          obj.village = obj.village.id
          obj.villager = obj.villager.id
          obj.upMessage = value
          obj.status += 1
          const res = await this.$http.patch(`feedback/${feedback.id}`, obj)
          if (res.status == 200) {
            this.$baseMessage("向上反馈成功", "success");
            this.fetchData()
          } else {
            this.$baseMessage("向上反馈失败", "error");
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });       
        });
        
      });
    },
    async returnFeedback(feedback) {
      this.$baseConfirm("你确定要退回当前项吗", null, async () => {
        let obj = JSON.parse(JSON.stringify(feedback))
        obj.village = obj.village.id
        obj.villager = obj.villager.id
        obj.status -= 1
        const res = await this.$http.patch(`feedback/${feedback.id}`, obj)
        if (res.status == 200) {
          this.$baseMessage("退回反馈成功", "success");
          this.fetchData()
        } else {
          this.$baseMessage("退回反馈失败", "error");
        }
      });
    },
    async handleFeedback(handlingFeedback) {
      if(handlingFeedback.reseted) {
        this.res.handlRes = handlingFeedback.handlRes
      }

      this.handlingFeedback = handlingFeedback

      handlingFeedback = JSON.parse(JSON.stringify(handlingFeedback))

      // console.log(handlingFeedback)

      this.documents = handlingFeedback.relatedDocuments
      this.relatedDocuments = handlingFeedback.relatedDocuments

      const town = await this.$http.get(`town/${handlingFeedback.village.town.id}?join=area`)

      handlingFeedback.villageWrap = [town.data.area.id, handlingFeedback.village.town.id, handlingFeedback.village.id];
      this.change(handlingFeedback.villageWrap)
      //处理关联
      handlingFeedback.village = handlingFeedback.village.id
      handlingFeedback.villager = handlingFeedback.villager.id

      this.title = "编辑";
      this.showForm = Object.assign({}, handlingFeedback);

      this.dialogFormVisible = true
    },
    async handle(feedback) {
      feedback = JSON.parse(JSON.stringify(this.handlingFeedback))
      this.res.handler = this.user.id
      feedback.village = feedback.village.id
      feedback.villager = feedback.villager.id
      const res = await this.$http.patch(`feedback/${feedback.id}`, {
        ...feedback,
        ...this.res
      })
      if (res.status == 200) {
        this.$baseMessage("处理反馈成功", "success");
        this.dialogFormVisible = false
        this.fetchData()
      } else {
        this.$baseMessage("处理反馈失败", "error");
      }
    },
    async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      const formData = new FormData();
      formData.append("file", file);
      const res = await this.$http.post("/admin-api/app/upload", formData);
      if (res.status == 200) {
          this.$baseMessage("图片上传成功", "success");
        } else {
          this.$baseMessage("图片上传失败", "error");
        }
      Editor.insertEmbed(cursorLocation, "image", res.data.url);
      resetUploader();
    },
  },
};
</script>
